package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.dtos.WmNewsUpOrDownDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.WmThreadLocalUtil;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private WmUserService wmUserService;

    /*@Autowired
    private WmNewsTaskService wmNewsTaskService;*/

    /**
     * 条件查询自媒体文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        dto.checkParam();

        //2.分页
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //文章状态
        if (dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道
        if (dto.getChannelId() != null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //发布时间区间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        page = page(page,lambdaQueryWrapper);

        //3，返回结果
        return new PageResponseResult(page);
    }

    /**
     * 自媒体文章提交或存草稿
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.校验参数
        if (dto == null || StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        if (dto.getImages() != null || dto.getImages().size() > 0){
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        //如果当前封面类型为自动 -1
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO){
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);

        //3.判断是否为草稿，为草稿则停止方法
        if (dto.getStatus() == WmNews.Status.NORMAL.getCode()){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //4.不是草稿则新增文章内容图片与素材的关联
        //获取到文章内容中的图片信息
        List<String> contentImgs =  extractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(contentImgs,wmNews.getId());

        //5.不是草稿则新增文章封面图片与素材的关联，若当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto,wmNews,contentImgs);

        //异步添加到延迟队列
        //wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsUpOrDownDto dto) {
        //1.校验参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断是否已发布
        if (wmNews.getStatus() != WmNews.Status.PUBLISHED.getCode()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章enable
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate()
                    .set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,wmNews.getId()));
            //发消息通知article端
            if (wmNews.getArticleId() != null){
                Map<String,Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",dto.getEnable());
                String data = JSON.toJSONString(map);
                log.info("开始发消息通知article端，articleId={}",wmNews.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,data);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 分页查询待人工审核文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult auditPageList(NewsAuthDto dto) {
        //检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();

        //分页
        IPage page = new Page(dto.getPage(),dto.getSize());
        //条件匹配
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper();

        if (StringUtils.isNotBlank(dto.getTitle())){  //标题
            wrapper.like(WmNews::getTitle,dto.getTitle());
        }
        if (dto.getStatus() != null){  //状态
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        } else {
            //查全部文章只取这四个状态的文章
            wrapper.in(WmNews::getStatus,
                    WmNews.Status.FAIL.getCode(),WmNews.Status.ADMIN_AUTH.getCode(),
                    WmNews.Status.ADMIN_SUCCESS.getCode(),WmNews.Status.PUBLISHED.getCode());

        }
        //查询
        page = page(page,wrapper);

        //处理结果
        List<WmNews> wmNewsList = page.getRecords();
        //最终结果集
        List<WmNewsVo> newsVoList = new ArrayList<>();
        if (wmNewsList != null && wmNewsList.size() > 0){
            Map<Integer, List<WmNews>> userIdWmNewsMap = wmNewsList.stream()
                    .collect(Collectors.groupingBy(WmNews::getUserId));
            //按照userId从小到大排序
            Map<Integer, List<WmNews>> sortedMap = new TreeMap<>(userIdWmNewsMap);
            //根据id查询对应user
            List<WmUser> wmUserList = wmUserService.list(Wrappers.<WmUser>lambdaQuery().in(WmUser::getId, sortedMap.keySet()));

            //构造  user -->  newsList的数据
            Map<WmUser,List<WmNews>> userNewsMap = new HashMap<>();
            int i = 0;
            for (List<WmNews> newsList : sortedMap.values()) {
                userNewsMap.put(wmUserList.get(i++),newsList);
            }

            //构造 WmNewsVo 结果集
            for (Map.Entry<WmUser, List<WmNews>> entry : userNewsMap.entrySet()) {
                for (WmNews wmNews : entry.getValue()) {
                    WmNewsVo newsVo = new WmNewsVo();
                    BeanUtils.copyProperties(wmNews,newsVo);
                    newsVo.setAuthorName(entry.getKey().getName());
                    newsVoList.add(newsVo);
                }
            }
        }

        //封装结果到page中
        page.setRecords(newsVoList);
        return new PageResponseResult(page);
    }

    /**
     * 平台管理查看文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult getOneById(Integer id) {
        //检查参数
        if (id != null){
            WmNews news = getById(id);
            if (news != null){
                return ResponseResult.okResult(news);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
    }

    /**
     * 平台管人工审核文章通过
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        //1.检查参数
        if (dto.getStatus() == null || dto.getId() == null
                || dto.getStatus().shortValue() != WmNews.Status.ADMIN_SUCCESS.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.1根据id获取要审核的文章
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId,dto.getId()).eq(WmNews::getStatus,WmNews.Status.ADMIN_AUTH.getCode());
        WmNews wmNews = getOne(wrapper);
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.3将其添加到延迟任务
        //wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        //更新状态为待发布
        wmNews.setStatus(WmNews.Status.SUCCESS.getCode());
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 平台管人工审核文章失败
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        //1.检查参数
        if (dto.getStatus() == null || dto.getId() == null
                || dto.getStatus().shortValue() != WmNews.Status.FAIL.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.1根据id获取要审核的文章
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId,dto.getId()).eq(WmNews::getStatus,WmNews.Status.ADMIN_AUTH.getCode());
        WmNews wmNews = getOne(wrapper);
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.3将其添加到延迟任务
        //wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        //更新状态为审核失败
        wmNews.setStatus(WmNews.Status.FAIL.getCode());
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 第二个功能：保存封面图片与素材的关系
     * @param dto
     * @param wmNews
     * @param contentImgs
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> contentImgs) {
        List<String> images = dto.getImages();
        //1.如果当前封面类型为自动
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO){

            //1.1 无图封面
            if (contentImgs.size() <= 0 || contentImgs == null){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            }

            //1.2 单图封面
            if (contentImgs.size() >= WemediaConstants.WM_NEWS_SINGLE_IMAGE &&
                    contentImgs.size() < WemediaConstants.WM_NEWS_MANY_IMAGE){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = contentImgs.stream().limit(1).collect(Collectors.toList());
            }

            //1.3 三图封面
            if (contentImgs.size() >= WemediaConstants.WM_NEWS_MANY_IMAGE){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
               images = contentImgs.stream().limit(3).collect(Collectors.toList());
            }

            //修改自媒体文章
            wmNews.setImages(StringUtils.join(images,","));
            updateById(wmNews);
        }

        //2.保存封面图片与素材的关系
        if (images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }

    /**
     * 处理文章内容图片与素材的关系
     * @param contentImgs
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> contentImgs, Integer newsId) {
        saveRelativeInfo(contentImgs,newsId,WemediaConstants.WM_CONTENT_REFERENCE);

    }

    /**
     * 保存文章图片与素材的关系
     * @param imgs
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> imgs, Integer newsId, Short type) {
        if (imgs != null && imgs.size() > 0){
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(new LambdaQueryWrapper<WmMaterial>().in(WmMaterial::getUrl,imgs));
            if (wmMaterials == null || wmMaterials.size() == 0 || imgs.size() != wmMaterials.size()){
                throw  new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            wmNewsMaterialMapper.batchInsert(materialIds,newsId,type);
        }
    }

    private List<String> extractUrlInfo(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> contentImgs = new ArrayList();
        for (Map map : list) {
            if (map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)){
                contentImgs.add((String)map.get("value"));
            }
        }

        return contentImgs;
    }

    /**
     * 新增或修改自媒体文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_ENABLE_GROUNDING); //默认上架
        //新增
        if (wmNews.getId() == null){
            save(wmNews);
        }

        //修改
        //删除文章和素材关联
        wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        updateById(wmNews);
    }
}
